package com.laicunba.event.listener;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.RedemptionTransferEvent;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.pojo.WithdrawDO;
import com.laicunba.service.MobileMessageService;
import com.laicunba.service.TemplateService;
import com.laicunba.service.UserService;
import com.laicunba.service.WithdrawService;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

@Component
public class RedemptionTransferListener implements ApplicationListener<RedemptionTransferEvent> {
	@Autowired
	private TemplateService templateService;
	@Autowired
	private MobileMessageService mobileMessageService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private UserService userService;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void onApplicationEvent(RedemptionTransferEvent event) {
		if (!(event.getSource() instanceof HashMap)) {
			return;
		}
		Map map = (Map) event.getSource();
		String withdrawId = (String) map.get("withdrawId");
		String type = (String) map.get("type");
		if (StringUtil.hasEmpty(withdrawId, type)) {
			return;
		}

		// 发短信通知用户
		WithdrawDO withdrawDO = withdrawService.get(WithdrawDO.class, withdrawId);
		String notifyMesssage = "";
		Map values = new HashMap();
		values.put("amount", withdrawDO.getWithdrawPrincipal());

		if ("T0".equalsIgnoreCase(type)) {
			TemplateDO templateDO = templateService.findByCodeWidthDefault("JZH_REDEMPTION_TRANSFERRED_T0");
			notifyMesssage = templateService.simpleMerge(templateDO.getContent(), values);
		}
		if ("T1".equalsIgnoreCase(type)) {
			TemplateDO templateDO = templateService.findByCodeWidthDefault("JZH_REDEMPTION_TRANSFERRED_T1");
			values.put("date", DateUtil.formatDate(new Date()));
			notifyMesssage = templateService.simpleMerge(templateDO.getContent(), values);
		}
		UserDO userDO = userService.get(UserDO.class, withdrawDO.getUserId());
		mobileMessageService.sendMsgAsync(userDO.getMobile(), notifyMesssage);
	}

}
